package com.xiaxueqi.web.home;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.web.struts2.Struts2Utils;

import com.niagara.context.SecurityContext;
import com.niagara.security.auth.entity.UserDetail;
import com.niagara.security.auth.exception.AuthException;
import com.niagara.service.base.BaseService;
import com.niagara.web.struts2.CRUDActionSupport;
import com.octo.captcha.service.CaptchaService;
import com.octo.captcha.service.CaptchaServiceException;
import com.xiaxueqi.entity.book.BookForsale;
import com.xiaxueqi.entity.book.BookStore;
import com.xiaxueqi.service.UploadService;

public class UploadBookAction extends CRUDActionSupport<BookStore> {
	private static final long serialVersionUID = -6226987124261483027L;

	@Autowired
	private BaseService baseService;
	private BookStore book;
	private BookForsale bookForsale;
	private Integer id;
	private File myFile;
	private String myFileFileName;
	private String myFileContentType;
	private String savePath;
	@Autowired
	private UploadService uploadService;

	private UserDetail detail = SecurityContext.getUserDetail();
	private Integer userId = detail != null ? Integer.valueOf(detail
			.getUserId().intValue()) : null;

	private String captcha;
	private CaptchaService captchaService;
	private String captchaError;

	public String getCaptchaError() {
		return captchaError;
	}

	public CaptchaService getCaptchaService() {
		return captchaService;
	}

	public void setCaptchaService(CaptchaService captchaService) {
		this.captchaService = captchaService;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

	@Override
	public String list() {
		return null;
	}

	@Override
	public String delete() throws Exception {
		return null;
	}

	@Override
	public String input() throws Exception {
		return INPUT;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (this.id != null) {
			this.book = this.baseService.get(BookStore.class, this.id);
		} else {
			this.book = new BookStore();
		}
		this.bookForsale = new BookForsale();
	}

	// 下面是具体的保存方法，上传所需要的配置
	@Override
	@Action(results = { @Result(name = SUCCESS, location = "book-manager.action", type = "redirect") }, interceptorRefs = {
			@InterceptorRef(value = "fileUpload", params = {
					"allowedTypes",
					"image/bmp,image/x-png,image/gif,image/pjpeg,image/jpg,image/JPG,image/JPEG,image/jpeg",
					"maximumSize", "1024000" }),
			@InterceptorRef(value = "crudStack"),
			@InterceptorRef(value = "defaultStack") }, params = { "savePath",
			"/upload" })
	public String save() throws Exception {
		HttpServletRequest request = SecurityContext.getRequest();
		String captchaID = request.getSession().getId();
		boolean success = false;
		try {
			success = captchaService.validateResponseForID(captchaID, captcha);
		} catch (CaptchaServiceException e) {
			logger.error(e.getMessage(), e);
			throw new AuthException(e);
		}
		if (!success) {
			this.captchaError = "error";
			// return 一个没有定义的跳转"stop"，将只将本页面刷新
			return "stop";
		}
		if (book.getId() != null) {
			this.baseService.update(book);
		} else {
			try {
				String imgPath = null;
				if (myFile != null) {
					imgPath = this.uploadService.upload(this.myFile, this
							.getMyFileFileName(), this.savePath);
					// 下面是上传测试
					System.out.println("您上传的文件类型是："
							+ this.getMyFileContentType());
				}
				// 开始插入数据库
				book.setImgPath(imgPath);
				this.baseService.insert(book);
				bookForsale.setBookId(book.getId());
				bookForsale.setOwnerId(userId);
				bookForsale.setImgPath(imgPath);
				bookForsale.setStatus("unsale");
				bookForsale.setContent(Struts2Utils.getParameter("content"));
				bookForsale.setCount(Integer.valueOf(Struts2Utils
						.getParameter("count")));
				bookForsale.setPrice(Double.valueOf(Struts2Utils
						.getParameter("sell_price")));
				this.baseService.insert(bookForsale);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		addActionMessage("保存成功");
		return SUCCESS;
	}

	public BookStore getModel() {
		return this.book;
	}

	// 下面是必不可少的get,set方法
	public void setId(Integer id) {
		this.id = id;
	}

	public String getMyFileFileName() {
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}

	public String getMyFileContentType() {
		return myFileContentType;
	}

	public void setMyFileContentType(String myFileContentType) {
		this.myFileContentType = myFileContentType;
	}

	public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

}
